<template>
  <div class="up">
    <van-uploader
      accept="*"
      v-model="imgList"
      :after-read="afterRead"
      :before-read="beforeRead"
      preview-size="25vw"
      @click-preview="handleclicksc"
      :before-delete="afterDelete"
      :preview-full-image="false"
      :disabled="isUploading"
    />

    <!--点击图片或视频出现放大图片或播放视频的弹窗-->
    <van-overlay :show="show" @click="show = false">
      <div class="topper">
        <div class="img-block">
          <img v-if="urlType === 'image'" :src="url" />
          <video
            autoplay
            class="video"
            v-if="urlType === 'video'"
            :src="url"
            controls
          ></video>
        </div>
        <!--给视频添加关闭图标-->
        <img
          v-if="urlType === 'video'"
          @click="show = false"
          class="video-delete"
          src="./close.png"
        />
      </div>
    </van-overlay>
  </div>
</template>

<script setup>
import http from "@/utils/request.js";
import { reactive, ref, watch } from "vue";

const isUploading = ref(false);
const allInfoList = reactive([]);
const url = ref("");
const urlType = ref("");
const imgList = reactive([]);
defineExpose({
  imgList,
});
//限制上传的内容为视频或图片
function beforeRead(file) {
  if (!file.type.startsWith("image") && !file.type.startsWith("video")) {
    this.$toast("请上传图片或视频");
    return false;
  }
  return true;
}

function afterRead(file) {
  file.status = "uploading";
  file.message = "上传中...";
  //添加上传状态，避免用户在上传未完成时点击提交按钮
  console.log(file.file);
  isUploading.value = true;
  let formData = new FormData();
  formData.append("file", file.file);
  let config = {
    headers: {
      //添加请求头
      "Content-Type": "multipart/form-data",
    },
  };
  http
    .post("/upload/image", formData, config)
    .then((res) => {
      console.log(res);
      if (res.data.code === "200") {
        let fileDTO = {
          type: res.data.type,
          url: res.data.url,
        };
        //为返回的数据添加文件类型，后面依据此来判断
        // if (file.file.type.startsWith('video')) {
        //   fileDTO.type = 'video'
        // }
        // if (file.file.type.startsWith('image')) {
        //   fileDTO.type = 'image'
        // }
        //将返回的所有数据都保存起来（文件地址，文件名等）
        allInfoList.push(fileDTO);
      } else {
        //上传失败要清空数组，不然失败的文件依旧会展示
        handleDelete(file.file.name);
      }
      file.status = "";
      file.message = "";
      isUploading.value = false;
    })
    .catch((error) => {
      console.log(error);
      handleDelete(file.file.name);
      file.status = "";
      file.message = "";
      isUploading.value = false;
    });
}

//根据文件名来查找到文件列表中要删除的文件
function handleDelete(name) {
  imgList.forEach((item, index) => {
    if (item.file.name === name) {
      imgList.splice(index, 1);
    }
  });
}

//手动点击删除，修改包含所有信息的文件列表，通过watch根据该列表动态修改图片文件列表
function afterDelete(file) {
  let name = file.name;
  allInfoList.forEach((item, index) => {
    if (item.originalName === name) {
      allInfoList.splice(index, 1);
    }
  });
  return true;
}

//取消掉组件自带的点击预览功能，自己添加（系统自带预览点击视频时会先视频的播放图片）
function handleclicksc(file) {
  let name = file.name;
  for (let item of allInfoList) {
    if (item.type === "video" && item.originalName === name) {
      url.value = this.getUrl(item.fileUri);
      urlType.value = "video";
      this.show = true;
    }
    if (item.type === "image" && item.originalName === name) {
      url.value = this.getUrl(item.fileUri);
      urlType.value = "image";
      this.show = true;
    }
  }
}

watch(allInfoList, () => {
  for (let item of allInfoList) {
    let data = {
      url:
        item.type === "video"
          ? "http://replacement.png"
          : "http://127.0.0.1:8080" + item.url,
    };
    imgList.push(data);
  }
});
</script>

<style>
.up {
  position: relative;
  top: 170px;
  left: 15%;
}

.topper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.img-block {
  position: relative;
  /* img {
    z-index: 99;
    max-width: 100%;
    height: auto;
    object-fit: cover;
  } */
  /* video {
    width: 100%;
    max-height: 100vh;
  } */
}

.video-delete {
  width: 45px;
  position: absolute;
  top: 60px;
  left: calc(100vw - 60px);
}
</style>
